#include "command.h"


int _ls(char *argv[])
{
	/* check the number of cmd-line parameters is correct */
	int argc = 0;
	for (char **ptr = argv; *ptr != NULL; ptr++)
		argc++;

	if (argc > 3) {
		fprintf(stderr, "Usage: ls [-a] [directory]\n");
		return -1;
	}

	int opt; 					/* option character */
	const char *opt_fmt = "a"; 	/* option format */
	int print_hidden_file = 0;

	/* parse the cmd-line parameters */
	while ((opt = getopt(argc, argv, opt_fmt)) != -1) {
		switch (opt) {
			case 'a': 
				print_hidden_file = 1;
				break;
			default:
				fprintf(stderr, "Usage: ls [-a] [directory]\n");
				return -1;
		}
	}

	/* Get the directory name and open it */
	// const char *directory = (argc > 1) ? argv[1] : ".";
	const char *directory;
	if (argv[optind]) {
		directory = argv[optind];
	} else {
		directory = ".";
	}

	direntry_t *de; 			// store the directory entries
	de = get_list_files(directory);
	if (de == NULL) {
		fprintf(stderr, "ls error: get_list_files\n");
		return -1;
	}

	// print the result 
	print_list_files(de, print_hidden_file, NULL);

	free(de);
	return 0;
}
